from rest_framework import serializers
from .models import SeckillGoods
from django.utils.timezone import now

class GoodsListSerializer(serializers.ModelSerializer):
    goods_name = serializers.CharField(source="goods.goods_name", read_only=True)
    goods_img = serializers.CharField(source="goods.goods_img", read_only=True)
    goods_price = serializers.DecimalField(
        source="goods.goods_price",
        max_digits=12,
        decimal_places=2,
        read_only=True
    )

    class Meta:
        model = SeckillGoods
        fields = [
            'id',
            'goods_name',       # 商品名称
            'goods_img',        # 商品图片
            'goods_price',      # 商品原价
            'seckill_price',    # 秒杀价格
            'stock_count'       # 秒杀库存
        ]


class GoodsDetailSerializer(serializers.ModelSerializer):
    goods_name = serializers.CharField(source="goods.goods_name", read_only=True)
    goods_img = serializers.CharField(source="goods.goods_img", read_only=True)
    goods_price = serializers.DecimalField(
        source="goods.goods_price",
        max_digits=12,
        decimal_places=2,
        read_only=True
    )
    remain_seconds = serializers.SerializerMethodField()
    sec_kill_status = serializers.SerializerMethodField()
    start_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    end_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    class Meta:
        model = SeckillGoods
        fields = [
            'id',
            'goods_name',       # 商品名称
            'goods_img',        # 商品图片
            'goods_price',      # 商品原价
            'seckill_price',    # 秒杀价格
            'stock_count',      # 秒杀库存
            'start_date',       # 秒杀开始时间
            'end_date',         # 秒杀结束时间
            'remain_seconds',   # 剩余秒数
            'sec_kill_status'   # 秒杀状态
        ]

    def get_remain_seconds(self, obj):
        """计算秒杀倒计时剩余秒数"""
        if not obj.start_date:
            return -1
        else:
            remaining = (obj.start_date - now()).total_seconds()
            return max(int(remaining), 0)

    def get_sec_kill_status(self, obj):
        """判断秒杀状态"""
        current_time = now()
        if obj.start_date and obj.end_date:
            if current_time < obj.start_date:
                return 0  # 秒杀倒计时
            elif obj.start_date <= current_time <= obj.end_date:
                return 1  # 秒杀进行中
            else:
                return 2  # 秒杀已结束
        return 2  # 默认为秒杀已结束